/*******************************************************************************
 *
 *      Filename: Application.cpp
 *   Description: See Application.h
 *        Author: [kb]ypp
 *    Created at: November 28, 2005
 *
 ******************************************************************************/

#include "Application.h"
#include "GLWindow.h"
#include "Log.h"
#include "Scene.h"
#include "Timer.h"
#include <cassert>
#include <string>
#include <vector>
using namespace std;

//! @arg title - Rendering window title
//! @arg width - Rendering window width
//! @arg hight - Rendering window hight
//! @arg fs    - Fullscreen? (If fs == true than fullscreen mode)
Application::Application( const string &title, int w, int h, bool fs )
    : window_( new GLWindow( *this, w, h, fs ) ), done_( false )
{
    window_->title( title );
}

Application::~Application()
{
    delete window_;
}

//! If scene pointer == 0 than warning message sent to log (no other actions
//! will be performed, only warning)
void Application::addScene( Scene *scene )
{
    if ( scene )
        sceneList_.push_back( scene );
    else
        LOG_ERROR( "Pointer to the new added scene = 0" );
}

void Application::resize( int width, int height )
{
    // renderer_.resize();
}

//! This function exits only on program exit
//!
void Application::run()
{
    assert( window_ );

    vector< Scene* >::iterator curScene = sceneList_.begin();
    if ( curScene == sceneList_.end() ) {
        LOG_WARNING( "No scenes specified" );
        done_ = true;
    } else
        ( *curScene )->init();

    LOG_NOTICE( "*** Entering main loop ***" );
    timer_.reset();
    timer_.start();
    while ( !done_ ) {
        window_->processEvents();

        // NOTICE: No scene interleaving performed (yet)
        ( *curScene )->update( timer_.delta() );
        ( *curScene )->render();

        window_->swapBuffers();
    }
    LOG_NOTICE( "*** Main loop finished ***" );
}

void Application::suspend()
{
    timer_.stop();
    LOG_NOTICE( "*** Application suspended ***" );
}

void Application::resume()
{
    timer_.start();
    LOG_NOTICE( "*** Application resumed ***" );
}

void Application::quit()
{
    done_ = true;
}
